package com.mrd.gtimp.business.action;

import com.mrd.constant.BaseTypeConstant;
import com.mrd.constant.MsgConstants;
import com.mrd.constant.RoleConstants;
import com.mrd.constant.SpecialConstant;
import com.mrd.constant.SystemConstants;
import com.mrd.exception.QueryException;
import com.mrd.framework.config.web.json.Result;
import com.mrd.framework.ui.Jqgrid;
import com.mrd.framework.ui.filter.Filter;
import com.mrd.framework.ui.filter.FilterGroupOption;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.framework.utils.HttpUtils;
import com.mrd.gtimp.base.entity.SystemValue;
import com.mrd.gtimp.base.entity.User;
import com.mrd.gtimp.base.service.SystemValueBiz;
import com.mrd.gtimp.business.BusinessDto;
import com.mrd.gtimp.business.entity.Attachment;
import com.mrd.gtimp.business.entity.Booking;
import com.mrd.gtimp.business.entity.Goods;
import com.mrd.gtimp.business.entity.Trail;
import com.mrd.gtimp.business.service.BookingBiz;
import com.mrd.gtimp.business.service.GoodsBiz;
import com.mrd.gtimp.business.service.TrailBiz;
import com.mrd.util.ReflectUtil;
import com.mrd.util.sendEmail.SendEmail;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import static com.mrd.util.AdminUtil.checkRight;


/**
 * <p> application name: gtimp <p> copyright: Copyright@2012 明睿达科技有限公司
 */

/**
 * @author luob
 */

@Controller
@RequestMapping("/business")
public class BookingAction {
    private static final long serialVersionUID = 1L;
    @Resource
    private BookingBiz bookingBiz;
    @Resource
    private SystemValueBiz systemValueBiz;
    @Resource
    private GoodsBiz goodsBiz;

    @Resource
    private TrailBiz trailBiz;


    /**
     * 默认访问入口
     */
    @RequestMapping("/booking-main")
    public String main() {
        return "/gtimp/booking/bookinglist";
    }

    /**
     * 默认新增修改入口
     */
    @RequestMapping("/booking-manage")
    public String manage() {
        return "manage";
    }

    /**
     * 业务查看入口
     */
    @RequestMapping("/booking-bizView")
    public String bizView() {
        findForSupToValidate(new BusinessDto(), new Booking(), new Jqgrid());
        return "/gtimp/booking/bookingInfoForView";
    }


    /**
     * 业务修改入口
     */
    @RequestMapping("/booking-bizModify")
    public String bizModify() {
        return "/gtimp/booking/bookingInfoForModify";
    }

    /**
     * 检查业务是否可以进入修改页面
     */
    @RequestMapping("/booking-checkBizModify")
    @ResponseBody
    public Result checkBizModify() {
        Result msg;
        String id = HttpUtils.getParam("id");
        if (StringUtils.isNotEmpty(id)) {
            try {
                String hql = "select booking.bookingState from com.mrd.gtimp.business.pojo.Booking booking where booking.id='"
                        + id + "'";
                List<Object> objlist = bookingBiz.findObjectByHql(hql, 0, 1, null);
                if (null != objlist && objlist.size() == 1) {
                    if (BaseTypeConstant.BOOKINGSTATE_03.equals(objlist.get(0))
                            || BaseTypeConstant.BOOKINGSTATE_00.equals(objlist.get(0))) {
                        msg = Result.newSuccessInstance(MsgConstants.CHECK_SUCCESS);
                    } else {
                        msg = Result.newFailInstance(MsgConstants.CHECK_FAIL);
                    }
                } else {
                    msg = Result.newFailInstance(MsgConstants.SYSTEM_ERROR);
                }
            } catch (Exception e) {
                e.printStackTrace();
                msg = Result.newFailInstance(MsgConstants.SYSTEM_ERROR);
            }
        } else {
            msg = Result.newFailInstance(MsgConstants.SYSTEM_ERROR);
        }
        return msg;
    }

    /**
     * 检查业务是否可以进行提交操作
     */
    @RequestMapping("/booking-checkBizConfirm")
    public Result checkBizConfirm() {
        return checkBizModify();
    }

    /**
     * 业务提交
     * @return
     */
    /**
     * 从修改页面传回的 id
     */
    private String id;

    // String id = HttpUtils.getParam("id");

    @RequestMapping("/booking-bizConfirm")
    @ResponseBody
    public Result bizConfirm(User user, Booking booking) {
        Result msg;
        try {
            System.out.println(id);
            booking = bookingBiz.findEntityById(id);
            if (booking.getBookingState().equals(BaseTypeConstant.BOOKINGSTATE_00)
                    || booking.getBookingState().equals(BaseTypeConstant.BOOKINGSTATE_03)) {
                bookingBiz.updateBizConfirm(id);
                msg = Result.newSuccessInstance(MsgConstants.OPERATION_SUCCESS);
                String businessId = booking.getBusinessId();
                // 提交后进行消息提醒
                // RobotService.sendMsgToUserClient("gtimp/biz/guanxx", businessId);
                // 邮件发送
                String user_email = user.getEmail();
                if (user_email != null) {
                    String body = "您已下单成功，业务编号为：" + businessId;
                    SendEmail.sendEmail(user_email, "货运平台下单通知", body);
                }
            } else {
                msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            }
        } catch (Exception e) {
            msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            e.printStackTrace();
        }
        return msg;
    }

    /**
     * 删除业务记录
     */
    @RequestMapping("/booking-bizDelete")
    public String bizDelete() {
        return "msg";
    }

    @RequestMapping("/booking-listForSupToValidate")
    public String listForSupToValidate() {
        return "/gtimp/booking/bookingInfoForSupToValidate";
    }

    /**
     * 新增或修改信息
     */
    @RequestMapping("/booking-saveOrUpdate")
    @ResponseBody
    public Result saveOrUpdate(Booking booking) {
        Result msg;
        if (checkRight(RoleConstants.SUP_CUSTOMER_SAVE)) {
            try {
                if (StringUtils.isEmpty(booking.getId())) { // 新增操作
                    // booking.setCOM_ID(user.getCompany().getId());
                    // booking.setCREATOR(user.getAccount());
                    // booking.setCTIME(new Date());
                    booking.setId(null);
                } else { // 修改操作
                    // booking.setMODIFIER(user.getAccount());
                    // booking.setMTIME(new Date());
                }
                bookingBiz.saveOrupdateEntity(booking);
                msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES);
            } catch (Exception e) {
                e.printStackTrace();
                msg = Result.newFailInstance(MsgConstants.SAVE_FAIL + e.getMessage());
            }
            return msg;
        }
        return Result.newFailInstance(SystemConstants.ROLE_FAIL);
    }

    /**
     * 在供应商处上传了so文件之后上传so号
     */
    @RequestMapping("/booking-updateSo")
    @ResponseBody
    public Result updateSo(User user) {
        Result msg;
        String bookId = HttpUtils.getParam("bookId");
        String so = HttpUtils.getParam("so");
        String isFinish = HttpUtils.getParam("isFinish");
        String validator = user.getAccount();
        try {
            List<String> pro = new ArrayList<String>();
            pro.add("so");
            Booking b = new Booking();
            b.setId(bookId);
            b.setSo(so);
            bookingBiz.updateEntity(b, pro);
            if ("1".equals(isFinish)) {
                bookingBiz.updateValidateFinish(bookId, validator);// 设置订舱业务的结束状态
                String result = replaceSoTohd(bookId);
                if ("SUCCESS".equals(result)) {
                    msg = Result.newSuccessInstance(MsgConstants.OPERATION_SUCCESS);
                } else {
                    msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
                }
            } else {
                msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES);
            }
        } catch (Exception e) {
            if ("1".equals(isFinish)) {
                msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            } else {
                msg = Result.newFailInstance(MsgConstants.SAVE_FAIL);
            }
            e.printStackTrace();
            return msg;
        }
        return msg;
    }

    /**
     * 编辑信息
     */
    @RequestMapping("/booking-find")
    @ResponseBody
    public List<SystemValue> find(Booking booking, BusinessDto businessDto) {
        if (null != booking) {
            if (StringUtils.isNotEmpty(booking.getId())) {
                try {
                    businessDto = new BusinessDto();
                    booking = bookingBiz.findEntityById(booking.getId());
                    String btype = booking.getBusinessType();
                    String sport = booking.getStPort();
                    String aport = booking.getArPort();
                    String hql = "from com.mrd.gtimp.base.pojo.SystemValue where identifier in ('"
                            + btype + "','" + sport + "','" + aport + "')";
                    List<SystemValue> objlist = systemValueBiz.findEntityByHql(hql, 0, 15, null);
                    for (SystemValue val : objlist) {
                        if (val.getIdentifier().equals(btype)) {
                            businessDto.setBookingBusinessType(val.getChn());
                        } else if (val.getIdentifier().equals(sport)) {
                            businessDto.setBookingStPort(val.getChn());
                        } else if (val.getIdentifier().equals(aport)) {
                            businessDto.setBookingArPort(val.getChn());
                        }
                    }
                    return objlist;
                } catch (QueryException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;

    }

    /**
     * 商品列表
     */
    @RequestMapping("/booking-findGoodsList")
    @ResponseBody
    public Page<Goods> findGoodsList(Booking booking) {
        if (null != booking) {
            if (StringUtils.isNotEmpty(booking.getId())) {
                try {
                    Filter filters = new Filter();
                    if (null == filters) {
                        filters = new Filter();
                        filters.setGroupOp(FilterGroupOption.AND);
                    }
                    SearchRule rule = new SearchRule("booking.id", SearchRuleOption.eq, booking.getId());
                    filters.addRule(rule);
//                    if (null != sidx && !"".equals(sidx)) {
//                        order.add(sidx, sord);
//                    }
//                    page = initPage(goodsBiz.findEntityCount(filters));
//                    goodses = goodsBiz.findByJqgrid(page.getCurrentPageStartNo(), page
//                            .getPageSize(), filters, order);
                    Pageable page = new PageRequest(0, 15, Sort.Direction.DESC);
                    Jqgrid jqgrid = new Jqgrid(filters, page);
                    Page<Goods> goodses = goodsBiz.findByJqgrid(jqgrid);
                    if (goodses.getSize() > 0) {
                        return goodses;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;

    }

    /**
     * 删除信息
     */
    @RequestMapping("/booking-del")
    @ResponseBody
    public Result del() {
        Result msg;
        if (checkRight(RoleConstants.SUP_CUSTOMER_DEL)) {
            try {
                // String ids = HttpUtils.getParam("id");
                // String[] idArr = ids.split(",");
                // StringBuffer sb = new StringBuffer();
                // for(String string : idArr) {
                // sb.append("'").append(string).append("',");
                // }
                // if(sb.length() > 0) {
                // sb.deleteCharAt(sb.length() - 1);
                // filters = new Filter();
                // filters.setGroupOp(FilterGroupOption.AND);
                // filters.addRule(new SearchRule("ID", SearchRuleOption.in, sb.toString()));
                // bookingBiz.deleteByFilter(filters);
                // }
                String ids = HttpUtils.getParam("id");
                Booking b = new Booking();
                b.setId(ids);
                bookingBiz.delete(b);
                msg = Result.newSuccessInstance(MsgConstants.DEL_SUCCES);
            } catch (Exception e) {
                e.printStackTrace();
                msg = Result.newFailInstance(MsgConstants.DEL_FAIL + e.getMessage());
            }
            return msg;
        }
        return Result.newFailInstance(SystemConstants.ROLE_FAIL);
    }

    /**
     * 查询
     *
     * @param loadPage 用来标识是否是载入历史页面传回的数据
     */
    @RequestMapping("/booking-findList")
    @ResponseBody
    public Page<Booking> findList(User user, String loadPage) {
        String comId = user.getCompany().getId();// 此处为客户
        List<Booking> bookings = null;
        Filter filters = null;
        try {
            if (StringUtils.isEmpty((CharSequence) filters)) {
                filters = new Filter();
                filters.setGroupOp(FilterGroupOption.AND);
            }
            SearchRule rule = new SearchRule("customer.id", SearchRuleOption.eq, comId);
            filters.addRule(rule);
//            page = initPage(bookingBiz.findEntityCount(filters));
//            Order order = new Order();
//            if (null != sidx && !"".equals(sidx)) {
//                order.add(sidx, sord);
//            }
            Pageable page = new PageRequest(0, 15, Sort.Direction.DESC, "id");

            String listCase = "select sval.chn, booking from com.mrd.gtimp.business.pojo.Booking booking, com.mrd.gtimp.base.pojo.SystemValue sval where booking.bookingState=sval.identifier ";
            String whereCase = "";
            if ("load".equals(loadPage)) {
                whereCase = whereCase + " and booking.bookingState in('BS02','BS04','BS05')";
            }
            if (null != filters.getRules() && filters.getRules().size() > 0) {
                for (SearchRule sr : filters.getRules()) {
                    String field = sr.getField();
                    Object data = sr.getData();
                    Field f = ReflectUtil.getField(sr.getField(), Booking.class);
                    boolean isDate = false;
                    if (f != null) {
                        if (f.getType().equals(Date.class)) {
                            data = "to_date('" + data + "','yyyy-MM-dd')";
                            isDate = true;
                        }
                    }
                    if (sr.getOp().equals(SearchRuleOption.eq)) {
                        whereCase = whereCase + " and booking." + field + " = '" + data + "' ";
                    } else if (sr.getOp().equals(SearchRuleOption.nc)) {
                        whereCase = whereCase + " and booking." + field + " not in ('" + data
                                + "') ";
                    } else if (sr.getOp().equals(SearchRuleOption.gt)) {
                        whereCase = whereCase + " and booking." + field
                                + (isDate ? " > " + data : " > '" + data + "'");
                    } else if (sr.getOp().equals(SearchRuleOption.lt)) {
                        whereCase = whereCase + " and booking." + field
                                + (isDate ? " < " + data : " < '" + data + "'");
                    } else if (sr.getOp().equals(SearchRuleOption.ge)) {
                        whereCase = whereCase + " and booking." + field
                                + (isDate ? " >= " + data : " >= '" + data + "'");
                    } else if (sr.getOp().equals(SearchRuleOption.le)) {
                        whereCase = whereCase + " and booking." + field
                                + (isDate ? " <= " + data : " <= '" + data + "'");
                    } else {
                        whereCase = whereCase + " and booking." + field + " like '%" + data + "%' ";
                    }
                }
            }
//            for (String key : order.keySet()) {
//                whereCase = whereCase + " order by booking." + key + " "
//                        + (order.get(key) ? "desc" : "asc") + " ";
//            }
//            List<Object> objList = bookingBiz.findObjectByHql(listCase, page
//                    .getCurrentPageStartNo(), page.getPageSize(), null);
            listCase = listCase + whereCase;
            Jqgrid jqgrid = new Jqgrid(filters, page);
            Page<Booking> objList = bookingBiz.findByJqgrid(jqgrid);
            if (null != objList && objList.getSize() > 0) {
                if (bookings == null) {
                    bookings = new ArrayList<Booking>();
                }
                for (Object o : objList) {
                    Object[] os = (Object[]) o;
                    Booking b = (Booking) os[1];
                    b.setBookingState(os[0].toString());
                    bookings.add(b);
                }
            }
            return objList;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 供应商业务审核详细页面
     */
    @RequestMapping("/booking-findForSupToValidate")
    public String findForSupToValidate(BusinessDto businessDto, Booking booking, Jqgrid jqgrid) {
        String id = HttpUtils.getParam("id");
        if (StringUtils.isNotEmpty(id)) {
            try {
                businessDto = new BusinessDto();
                booking = bookingBiz.findEntityById(id);
                String btype = booking.getBusinessType();
                String sport = booking.getStPort();
                String aport = booking.getArPort();
                String hql = "from com.mrd.gtimp.base.pojo.SystemValue where identifier in ('"
                        + btype + "','" + sport + "','" + aport + "')";
//                List<SystemValue> objlist = systemValueBiz.findEntityByHql(hql, 0, 15, null)
                Page<SystemValue> objlist = systemValueBiz.findByJqgrid(jqgrid);
                for (SystemValue val : objlist) {
                    if (val.getIdentifier().equals(btype)) {
                        businessDto.setBookingBusinessType(val.getChn());
                    } else if (val.getIdentifier().equals(sport)) {
                        businessDto.setBookingStPort(val.getChn());
                    } else if (val.getIdentifier().equals(aport)) {
                        businessDto.setBookingArPort(val.getChn());
                    }
                }
//                return  objlist;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "/gtimp/booking/bookingInfoForSupToValidate";
    }

    /**
     * 查询列表给供应商审核业务信息
     */
    @RequestMapping("/booking-findListForSupToValidate")
    @ResponseBody
    public String findListForSupToValidate(User user) {
        String comId = user.getCompany().getId();// 此处为供应商
        Filter filters = null;
        List<Booking> bookings = null;
        try {
            if (null == filters) {
                filters = new Filter();
                filters.setGroupOp(FilterGroupOption.AND);
            }
            SearchRule rule = new SearchRule("supCompany.id", SearchRuleOption.eq, comId);
            filters.addRule(rule);
            SearchRule rule2 = new SearchRule("bookingState", SearchRuleOption.nc, BaseTypeConstant.BOOKINGSTATE_00);
            filters.addRule(rule2);
//            page = initPage(bookingBiz.findEntityCount(filters));
//            Order order = new Order();
//            if (null != sidx && !"".equals(sidx)) {
//                order.add(sidx, sord);
//            }
            String listCase = "select sval.chn, booking from com.mrd.gtimp.business.pojo.Booking booking, com.mrd.gtimp.base.pojo.SystemValue sval where booking.bookingState=sval.identifier and (1=1 ";
            String whereCase = "";
            if (null != filters.getRules() && filters.getRules().size() > 0) {
                for (SearchRule sr : filters.getRules()) {
                    String field = sr.getField();
                    Object data = sr.getData();
                    if (field.equals("supCompany.id") || field.equals("trailState")) {
                        if (sr.getOp() == SearchRuleOption.eq) {
                            whereCase = whereCase + " and booking." + field + " = '" + data + "' ";
                        } else if (sr.getOp() == SearchRuleOption.nc) {
                            whereCase = whereCase + " and booking." + field + " not in ('" + data
                                    + "') ";
                        } else {
                            whereCase = whereCase + " and booking." + field + " like '%" + data
                                    + "%' ";
                        }
                    }

                }
            }
            // 业务流转查询
            whereCase = whereCase
                    + " or booking.id in (select bizId from com.mrd.gtimp.business.pojo.BizFlow where scompany='"
                    + comId + "' or tcompany='" + comId + "')) ";
            if (null != filters.getRules() && filters.getRules().size() > 0) {
                for (SearchRule sr : filters.getRules()) {
                    String field = sr.getField();
                    Object data = sr.getData();
                    Field f = ReflectUtil.getField(sr.getField(), Booking.class);
                    boolean isDate = false;
                    if (f != null) {
                        if (f.getType().equals(Date.class)) {
                            data = "to_date('" + data + "','yyyy-MM-dd')";
                            isDate = true;
                        }
                    }
                    if (!"supCompany.id".equals(field)
                            && !data.equals(BaseTypeConstant.BOOKINGSTATE_00)) {
                        if (sr.getOp() == SearchRuleOption.eq) {
                            whereCase = whereCase + " and booking." + field + " ='" + data + "' ";
                        } else if (sr.getOp() == SearchRuleOption.nc) {
                            whereCase = whereCase + " and booking." + field + " not in ('" + data
                                    + "') ";
                        } else if (sr.getOp().equals(SearchRuleOption.gt)) {
                            whereCase = whereCase + " and booking." + field
                                    + (isDate ? " > " + data : " > '" + data + "'");
                        } else if (sr.getOp().equals(SearchRuleOption.lt)) {
                            whereCase = whereCase + " and booking." + field
                                    + (isDate ? " < " + data : " < '" + data + "'");
                        } else if (sr.getOp().equals(SearchRuleOption.ge)) {
                            whereCase = whereCase + " and booking." + field
                                    + (isDate ? " >= " + data : " >= '" + data + "'");
                        } else if (sr.getOp().equals(SearchRuleOption.le)) {
                            whereCase = whereCase + " and booking." + field
                                    + (isDate ? " <= " + data : " <= '" + data + "'");
                        } else {
                            whereCase = whereCase + " and booking." + field + " like '%" + data
                                    + "%' ";
                        }
                    }
                }
            }
//            for (String key : order.keySet()) {
//                whereCase = whereCase + " order by booking." + key + " "
//                        + (order.get(key) ? "desc" : "asc") + " ";
//            }
            //            List<Object> objList = bookingBiz.findObjectByHql(listCase, page
//                    .getCurrentPageStartNo(), page.getPageSize(), null);
            listCase = listCase + whereCase;
            Pageable page = new PageRequest(0, 15, Sort.Direction.DESC, "gfDate");
            Jqgrid jqgrid = new Jqgrid(filters, page);
            Page<Booking> objList = bookingBiz.findByJqgrid(jqgrid);
            if (null != objList && objList.getSize() > 0) {
                if (bookings == null) {
                    bookings = new ArrayList<Booking>();
                }
                for (Object o : objList) {
                    Object[] os = (Object[]) o;
                    Booking b = (Booking) os[1];
                    b.setBookingState(SpecialConstant.VALIDATE_STATE_CUSTOMER_VIEW.equals(os[0]
                            .toString()) ? SpecialConstant.VALIDATE_STATE_SUP_VIEW : os[0]
                            .toString());
                    String realSupId = b.getRealSupId();
                    if (StringUtils.isNotEmpty(realSupId)) {
                        if (realSupId.equals(comId)) {
                            b.setRealSupId(realSupId + ":业务流入");
                        } else {
                            b.setRealSupId(realSupId + ":业务流出");
                        }
                    }
                    bookings.add(b);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    @Resource
    public void setBookingBiz(BookingBiz bookingBiz) {
        this.bookingBiz = bookingBiz;
    }

    @Resource
    public void setSystemValueBiz(SystemValueBiz systemValueBiz) {
        this.systemValueBiz = systemValueBiz;
    }


    @RequestMapping("/booking-checkValidatePass")
    @ResponseBody
    public Result checkValidatePass() {
        Result msg;
        String id = HttpUtils.getParam("id");
        String opType = HttpUtils.getParam("opType");
        if (StringUtils.isNotEmpty(id)) {
            try {
                String hql = "select booking.bookingState from com.mrd.gtimp.business.pojo.Booking booking where booking.id='"
                        + id + "'";
                List<Object> objlist = bookingBiz.findObjectByHql(hql, 0, 1, null);
                if (null != objlist && objlist.size() == 1) {
                    // if(BaseTypeConstant.BOOKINGSTATE_01.equals(objlist.get(0))) { //待审核
                    if ("tgsh".equals(opType) || "bh".equals(opType)) {
                        if (BaseTypeConstant.BOOKINGSTATE_01.equals(objlist.get(0))) {
                            msg = Result.newSuccessInstance(MsgConstants.CHECK_SUCCESS);
                        } else {
                            msg = Result.newFailInstance(MsgConstants.CHECK_FAIL);
                        }
                    } else {
                        if (BaseTypeConstant.BOOKINGSTATE_02.equals(objlist.get(0))) {
                            msg = Result.newSuccessInstance(MsgConstants.CHECK_SUCCESS);
                        } else {
                            msg = Result.newFailInstance(MsgConstants.CHECK_FAIL);
                        }
                    }
                } else {
                    msg = Result.newFailInstance(MsgConstants.SYSTEM_ERROR);
                }
            } catch (Exception e) {
                e.printStackTrace();
                msg = Result.newFailInstance(MsgConstants.SYSTEM_ERROR);
            }
        } else {
            msg = Result.newFailInstance(MsgConstants.SYSTEM_ERROR);
        }
        return msg;
    }

    public Result checkValidateReject() {
        return checkValidatePass();
    }

    @RequestMapping("/booking-validatePass")
    @ResponseBody
    public Result validatePass(Booking booking) {
        Result msg;
        try {
            String id = HttpUtils.getParam("id");
            booking = bookingBiz.findEntityById(id);
            if (null != booking
                    && booking.getBookingState().equals(BaseTypeConstant.BOOKINGSTATE_01)) {
                bookingBiz.updateValidatePass(id);
                msg = Result.newSuccessInstance(MsgConstants.OPERATION_SUCCESS);
            } else {
                msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            }
        } catch (Exception e) {
            msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            e.printStackTrace();
        }
        return msg;
    }

    @RequestMapping("/booking-validateReject")
    @ResponseBody
    public Result validateReject(Booking booking) {
        Result msg;
        try {
            String id = HttpUtils.getParam("id");
            booking = bookingBiz.findEntityById(id);
            if (null != booking
                    && booking.getBookingState().equals(BaseTypeConstant.BOOKINGSTATE_01)) {
                bookingBiz.updateValidateReject(id);
                msg = Result.newSuccessInstance(MsgConstants.OPERATION_SUCCESS);
            } else {
                msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            }
        } catch (Exception e) {
            msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            e.printStackTrace();
        }
        return msg;
    }


    @RequestMapping("/booking-validateUpload")
    @ResponseBody
    public Result validateUpload() {
        Result msg;
        String id = HttpUtils.getParam("id");
        try {
            bookingBiz.updateValidateUpload(id);
            msg = Result.newSuccessInstance(MsgConstants.OPERATION_SUCCESS);
        } catch (Exception e) {
            msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            e.printStackTrace();
        }
        return msg;
    }

    @RequestMapping("/booking-findBizState")
    @ResponseBody
    public Result findBizState() {
        Result msg = null;
        try {
            String id = HttpUtils.getParam("id");
            Booking entity = bookingBiz.findEntityById(id);
            //// TODO: 2016/8/13  service
//            SupBizServiceClient client = new SupBizServiceClient();
//            SupBaseBizQueryDTO qdto = new SupBaseBizQueryDTO();
//            // String serviceUrl = "http://localhost:8082/fhhd/ws/bookingBizService?wsdl";//本地
//            String serviceUrl = "http://219.130.222.62:9080/fhhd/ws/bookingBizService?wsdl";// 新港
//            qdto.setServiceUrl(serviceUrl);
//            String bizPk = entity.getBpk();
//            qdto.setBizPk(bizPk);
//            String result = client.findBookingBizState(qdto);
//            msg = result;
        } catch (Exception e) {
            msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            e.printStackTrace();
        }
        return msg;
    }

    @RequestMapping("/booking-findBizResult")
    public String findBizResult() {
        try {
            String id = HttpUtils.getParam("id");
            Booking entity = bookingBiz.findEntityById(id);

            //// TODO: 2016/8/13  service
//            SupBizServiceClient client = new SupBizServiceClient();
//            SupBaseBizQueryDTO qdto = new SupBaseBizQueryDTO();
//            // String serviceUrl = "http://localhost:8082/fhhd/ws/bookingBizService?wsdl";// 本地
//            String serviceUrl = "http://219.130.222.62:9080/fhhd/ws/bookingBizService?wsdl";// 新港
//            qdto.setServiceUrl(serviceUrl);
//            String bizPk = entity.getBpk();
//            qdto.setBizPk(bizPk);
//            SupBookingBizResultDTO result = client.findBookingBizResult(qdto);
//            HttpUtils.getRequest().setAttribute("resultDTO", result);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/gtimp/booking/bookingResult";
    }

    /**
     * 平台供应商管理员更新so到宏达系统
     */
    @RequestMapping("/booking-replaceSoTohd")
    public String replaceSoTohd(String bookId) {
        String result = "";
        try {
            Booking entity = bookingBiz.findEntityById(bookId);
            trailSynchroBooking(entity.getBusinessId(), entity.getSoDoc());
            //service
//            SupBizServiceClient client = new SupBizServiceClient();
//            SupBaseBizQueryDTO qdto = new SupBaseBizQueryDTO();
//            // String serviceUrl = "http://localhost:8082/fhhd/ws/bookingBizService?wsdl";// 本地
//            String serviceUrl = "http://219.130.222.62:9080/fhhd/ws/bookingBizService?wsdl";// 新港
//            qdto.setServiceUrl(serviceUrl);
//            String bizPk_1 = entity.getBpk();
//            String so = entity.getSo();
//            String bizPk = bizPk_1 + "_" + so;
//            qdto.setBizPk(bizPk);
//            result = client.replaceBookingBizSoTohd(qdto);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 当订舱和拖车一起下单的时候，最后的订舱上传的so文件要和拖车的一致
     */
    @RequestMapping("/booking-trailSynchroBooking")
    public void trailSynchroBooking(String busiId, Attachment soDoc) throws Exception {
        List<Trail> trail = trailBiz
                .findEntityByHql("from com.mrd.gtimp.business.pojo.Trail t where t.businessId='"
                        + busiId + "'", 0, 1, null);
        if (trail.size() == 0) {
            return;
        }
        String hql = "update com.mrd.gtimp.business.pojo.Trail t set t.soDoc='" + soDoc.getId()
                + "' where t.businessId = '" + busiId + "'";
        trailBiz.updateByHql(hql);
    }


    @Resource
    public void setGoodsBiz(GoodsBiz goodsBiz) {
        this.goodsBiz = goodsBiz;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }


}
